package com.imyours.net;

import java.util.ArrayList;
import java.util.List;

import javax.swing.plaf.basic.BasicViewportUI;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManagerFactory;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.imyours.net.exception.LoginException;
import com.imyours.net.exception.ShowException;
import com.imyours.net.messagedisposer.LoginMessageDisposer;
import com.imyours.net.messagedisposer.LogoutMessageDisposer;
import com.imyours.net.messagedisposer.MessageDisposer;
import com.imyours.net.messagedisposer.MyInfoMessageDisposer;
import com.imyours.net.messagedisposer.TeamListMessageDisposer;
import com.imyours.net.result.FriendListResult;
import com.imyours.net.result.LoginResult;
import com.imyours.net.result.LogoutResult;
import com.imyours.net.result.UserInfoResult;

public class NetLayer {

	private HttpClient hc = null;
	private String serviceUrl = "http://127.0.0.1:8080/imyours/imyours";
	private String sessionId = null;

	private void init() {
		ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
		hc = new DefaultHttpClient(cm);
	}

	/**
	 * 登陆方法
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return 执行结果
	 */
	public LoginResult login(String username, String password) {
		LoginResult exeresult = new LoginResult();
		exeresult.setSuccessed(false);
		try {
			if (username != null && password != null) {
				List<NameValuePair> paras = new ArrayList<NameValuePair>();
				paras.add(new BasicNameValuePair("username", username));
				paras.add(new BasicNameValuePair("password", password));
				paras.add(new BasicNameValuePair("service", "login"));
				String text = sendMsg(paras);
				if (text.length() == 0) {
					throw new ShowException("网络错误");
				}
				LoginMessageDisposer md = new LoginMessageDisposer(exeresult, text);
				if (exeresult.isSuccessed()) {
					this.sessionId = exeresult.getSessionId();
				}
			} else {
				throw LoginException.NO_EMPTY;
			}
		} catch (Exception ex) {
			exeresult.getExceptions().add(ex);
		}
		return exeresult;
	}

	/**
	 * 退出登陆方法
	 * 
	 * @return
	 */
	public LogoutResult logout() {
		LogoutResult result = new LogoutResult();
		try {
			if (sessionId == null) {
				throw new ShowException("尚未登录");
			}
			List<NameValuePair> paras = new ArrayList<NameValuePair>();
			paras.add(new BasicNameValuePair("sessionId", sessionId));
			paras.add(new BasicNameValuePair("service", "logout"));

			String text = sendMsg(paras);
			if (text.length() > 0) {
				MessageDisposer md = new LogoutMessageDisposer(result, text);
			} else {
				throw new ShowException("网络故障");
			}
		} catch (Exception ex) {
			result.addThrowAble(ex);
		}
		return result;
	}

	/**
	 * 查看我的信息
	 * 
	 * @return
	 */
	public UserInfoResult getMyInfo() {
		UserInfoResult result = new UserInfoResult();
		try {
			if (sessionId == null) {
				throw LoginException.NO_LOG;
			}
			List<NameValuePair> paras = new ArrayList<NameValuePair>();
			paras.add(new BasicNameValuePair("sessionId", this.sessionId));
			paras.add(new BasicNameValuePair("service", "userInfo"));
			String text = sendMsg(paras);
			new MyInfoMessageDisposer(result, text);
		} catch (Exception ex) {
			result.addThrowAble(ex);
		}
		return result;
	}

	/**
	 * 获取分组信息和好友列表
	 * 
	 * @return
	 */
	public FriendListResult friendList() {
		FriendListResult result = new FriendListResult();
		try {
			List<NameValuePair> paras = new ArrayList<NameValuePair>();
			paras.add(new BasicNameValuePair("service", "friendList"));
			paras.add(new BasicNameValuePair("sessionId", sessionId));
			String text = sendMsg(paras);
			new TeamListMessageDisposer(result, text);
		} catch (Exception e) {
			result.addThrowAble(e);
		}
		return result;
	}

	/**
	 * 创建分组信息
	 * 
	 * @param name
	 * @param order
	 */
	public void createTeam(String name, int order) {

		try {
			List<NameValuePair> paras = new ArrayList<NameValuePair>();
			paras.add(new BasicNameValuePair("service", "createTeam"));
			paras.add(new BasicNameValuePair("name", name));
			paras.add(new BasicNameValuePair("order", "" + order));
			paras.add(new BasicNameValuePair("sessionId", sessionId));

			String text = sendMsg(paras);
			System.out.println(text);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 修改分组信息
	 * 
	 * @param id
	 * @param name
	 * @param order
	 */
	public void modifyTeam(Long id, String name, int order) {
		try {
			List<NameValuePair> paras = new ArrayList<NameValuePair>();
			paras.add(new BasicNameValuePair("service", "modifyTeam"));
			paras.add(new BasicNameValuePair("sessionId", sessionId));
			paras.add(new BasicNameValuePair("name", "" + name));
			paras.add(new BasicNameValuePair("id", "" + id));
			paras.add(new BasicNameValuePair("order", "" + order));
			String text = sendMsg(paras);
			System.out.println(text);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**删除好友分组
	 * @param id
	 */
	public void removeTeam(long id) {
		try {
			List<NameValuePair> paras = new ArrayList<NameValuePair>();
			paras.add(new BasicNameValuePair("service", "removeTeam"));
			paras.add(new BasicNameValuePair("sessionId", sessionId));
			paras.add(new BasicNameValuePair("id", "" + id));
			String text = sendMsg(paras);
			System.out.println(text);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	
	/**添加好友到分组
	 * @param uid
	 * @param teamId
	 */
	public void addFriend(long uid,long teamId){
		try{
			List<NameValuePair> paras = new ArrayList<NameValuePair>();
			paras.add(new BasicNameValuePair("sessionId", sessionId));
			paras.add(new BasicNameValuePair("service", "addFriend"));
			paras.add(new BasicNameValuePair("userId", ""+uid));
			paras.add(new BasicNameValuePair("teamId", ""+teamId));
			String text = sendMsg(paras);
			System.out.println(text);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	/**从小组删除好友
	 * @param uid
	 * @param teamId
	 */
	public void removeFriend(long uid,long teamId){
		try{
			List<NameValuePair> paras = new ArrayList<NameValuePair>();
			paras.add(new BasicNameValuePair("sessionId", sessionId));
			paras.add(new BasicNameValuePair("service", "removeFriend"));
			paras.add(new BasicNameValuePair("userId", ""+uid));
			paras.add(new BasicNameValuePair("teamId", ""+teamId));
			String text = sendMsg(paras);
			System.out.println(text);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	/**
	 * 封装后的发送信息方法
	 * 
	 * @param paras
	 * @return 服务器响应
	 * @throws Exception
	 */
	protected String sendMsg(List<NameValuePair> paras) throws Exception {
		String result = "";

		HttpPost post = new HttpPost(serviceUrl);
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paras, "utf-8");
		post.setEntity(entity);
		HttpResponse response = hc.execute(post);
		result = EntityUtils.toString(response.getEntity(), "utf-8");
		return result;
	}

	// singleton
	private static NetLayer singleton = null;

	public static NetLayer getInstance() {
		if (singleton == null) {
			singleton = new NetLayer();
		}
		return singleton;
	}

	private NetLayer() {
		init();
	}

}
